
package com.xxxy.ljh.myapplication.DaoImpl;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.xxxy.ljh.myapplication.Dao.UserPointsRecordDao;
import com.xxxy.ljh.myapplication.dphelper.sqliteDBHelper;
import com.xxxy.ljh.myapplication.model.UserPointsRecord;

import java.util.ArrayList;
import java.util.List;

/**
 * 用户积分记录数据访问接口实现类。
 * 提供插入积分记录、根据用户ID查询积分记录、获取用户总积分以及积分排行榜功能。
 */
public class UserPointsRecordDaoImpl implements UserPointsRecordDao {
    private sqliteDBHelper dbHelper;

    /**
     * 构造方法，初始化数据库帮助类。
     *
     * @param context 上下文对象，用于创建数据库连接
     */
    public UserPointsRecordDaoImpl(Context context) {
        this.dbHelper = new sqliteDBHelper(context);
    }

    /**
     * 插入一条新的积分记录到数据库中。
     *
     * @param record 积分记录对象，包含要插入的数据
     * @return 返回新插入记录的行号，如果失败则返回-1
     */
    @Override
    public long insertPointsRecord(UserPointsRecord record) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("user_id", record.getUserId());
        values.put("total_points", record.getTotalPoints());
        values.put("source_type", record.getSourceType());
        values.put("related_id", record.getRelatedId());
        values.put("remark", record.getRemark());
        values.put("operate_user_id", record.getOperateUserId());

        return db.insert("user_points_record", null, values);
    }

    /**
     * 根据用户ID查询该用户的积分记录列表，并按创建时间倒序排列。
     *
     * @param userId 用户ID
     * @return 返回符合条件的积分记录列表
     */
    @Override
    public List<UserPointsRecord> getPointsRecordsByUserId(int userId) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        List<UserPointsRecord> records = new ArrayList<>();

        // 查询指定用户的所有积分记录并按照创建时间降序排序
        Cursor cursor = db.query("user_points_record", null,
                "user_id = ?", new String[]{String.valueOf(userId)},
                null, null, "create_time DESC");

        while (cursor.moveToNext()) {
            UserPointsRecord record = new UserPointsRecord();
            record.setRecordId(cursor.getInt(cursor.getColumnIndexOrThrow("record_id")));
            record.setUserId(cursor.getInt(cursor.getColumnIndexOrThrow("user_id")));
            record.setTotalPoints(cursor.getInt(cursor.getColumnIndexOrThrow("total_points")));
            record.setSourceType(cursor.getInt(cursor.getColumnIndexOrThrow("source_type")));
            record.setRelatedId(cursor.getInt(cursor.getColumnIndexOrThrow("related_id")));
            record.setRemark(cursor.getString(cursor.getColumnIndexOrThrow("remark")));
            record.setOperateUserId(cursor.getInt(cursor.getColumnIndexOrThrow("operate_user_id")));
            record.setCreateTime(cursor.getString(cursor.getColumnIndexOrThrow("create_time")));
            records.add(record);
        }
        cursor.close();
        return records;
    }

    /**
     * 获取指定用户的积分总和。
     *
     * @param userId 用户ID
     * @return 返回该用户的积分总数
     */
    @Override
    public int getTotalPointsByUserId(int userId) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        int totalPoints = 0;

        // 使用SQL语句计算指定用户的积分总和
        Cursor cursor = db.rawQuery(
                "SELECT SUM(total_points) as total FROM user_points_record WHERE user_id = ?",
                new String[]{String.valueOf(userId)});

        if (cursor.moveToFirst()) {
            totalPoints = cursor.getInt(cursor.getColumnIndexOrThrow("total"));
        }
        cursor.close();
        return totalPoints;
    }

    /**
     * 获取积分排行榜前N名的用户及其积分总和。
     *
     * @param limit 排行榜显示的数量限制
     * @return 返回积分排行榜列表，每个元素包括用户ID和其对应的积分总和
     */
    @Override
    public List<UserPointsRecord> getPointsRanking(int limit) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        List<UserPointsRecord> ranking = new ArrayList<>();

        // 按照用户分组统计积分总和，并取前limit条记录作为排行榜
        String query = "SELECT user_id, SUM(total_points) as total_points " +
                "FROM user_points_record " +
                "GROUP BY user_id " +
                "ORDER BY total_points DESC " +
                "LIMIT ?";

        Cursor cursor = db.rawQuery(query, new String[]{String.valueOf(limit)});

        while (cursor.moveToNext()) {
            UserPointsRecord record = new UserPointsRecord();
            record.setUserId(cursor.getInt(cursor.getColumnIndexOrThrow("user_id")));
            record.setTotalPoints(cursor.getInt(cursor.getColumnIndexOrThrow("total_points")));
            ranking.add(record);
        }
        cursor.close();
        return ranking;
    }
}